package main

import (
	"fmt"
	"io"
	"os"
	"time"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
)

var Program = "webport"

func loadConfig() {
	viper.SetConfigName(fmt.Sprintf(".%s", Program)) // name of config file (without extension)

	viper.AddConfigPath("$HOME") // path to look for the config file in
	viper.AddConfigPath(".")     // optionally look for config in the working directory

	viper.SetEnvPrefix(Program)
	viper.AutomaticEnv() // read in environment variables that match

	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
		} else {
			// Config file was found but another error was produced
			fmt.Fprintf(os.Stderr, "error reading config file: %v", err)
			os.Exit(1)
		}
	}
}

func initLogger() {
	// get config: log_level
	logLevelConf := viper.Get("log_level") // string or nil
	fmt.Printf("log_level: %v\n", logLevelConf)

	// set log level
	switch logLevelConf {
	case "trace":
		zerolog.SetGlobalLevel(zerolog.TraceLevel) // -1
	case "debug":
		zerolog.SetGlobalLevel(zerolog.DebugLevel) // 0
	case "info":
		zerolog.SetGlobalLevel(zerolog.InfoLevel) // 1
	case "warn":
		zerolog.SetGlobalLevel(zerolog.WarnLevel) // 2
	case "error":
		zerolog.SetGlobalLevel(zerolog.ErrorLevel) // 3
	case "fatal":
		zerolog.SetGlobalLevel(zerolog.FatalLevel) // 4
	case "panic":
		zerolog.SetGlobalLevel(zerolog.PanicLevel) // 5
	default:
		zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	}

	logWriters := make([]io.Writer, 0)
	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
	logWriters = append(logWriters, consoleWriter)

	logFileConf := viper.Get("log_file") // string or nil
	if logFileConf != nil {
		logFileName := logFileConf.(string)
		flag := os.O_APPEND | os.O_CREATE | os.O_WRONLY
		logFileHandle, err := os.OpenFile(logFileName, flag, 0644)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: cannot open log file \"%s\": %v", logFileName, err)
			os.Exit(1)
		}

		logWriters = append(logWriters, logFileHandle)
	}

	multi := zerolog.MultiLevelWriter(logWriters...)
	log.Logger = zerolog.New(multi).With().Timestamp().Logger()
}

func main() {
	loadConfig()
	initLogger()
	Execute()
}
